import { render, createVNode, shallowReactive } from 'vue';
import MessageConstructor from './main.vue';

let seed = 1;

const instances: any = shallowReactive([]);

const normalizeOptions = (params: any) => {
  const options = params
  const normalized = {
    ...options
  };
  if (!normalized.appendTo) {
    normalized.appendTo = document.body;
  }
  return normalized;
}

const closeMessage = (instance: any) => {
  const idx = instances.indexOf(instance);
  if (idx === -1)
    return;
  instances.splice(idx, 1);
  const { handler } = instance;
  handler.close();
};

const createMessage = ({ appendTo, ...options }: any, context: any) => {
  const id = `message_${seed++}`;
  const userOnClose = options.onClose;
  const container = document.createElement("div");
  const props = {
    ...options,
    id,
    onClose: () => {
      userOnClose == null ? void 0 : userOnClose();
      closeMessage(instance);
      render(null, container);
    }
  }

  const vnode: any = createVNode(MessageConstructor, props)
  console.log("props", props, vnode)
  vnode.appContext = context
  render(vnode, container)
  appendTo.appendChild(container.firstElementChild);

  const vm: any = vnode.component;
  const handler = {
    close: () => {
      vm.data.onClose();
    }
  };
  const instance = {
    id,
    vnode,
    vm,
    handler,
    props: vnode.component.props
  };
  return instance;
}

const Message = function (options: any, context?: any) {
  const normalized = normalizeOptions(options);
  const instance: any = createMessage(normalized, context);
  instances.push(instance);
  return instance.handler;
}

export default Message

